package org.terramagnet.workflow.dynamic.databinding.type;

import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 *
 * @author terrason
 */
public class EnumType extends BaseDataType<Integer> {

    private Map<Integer, String> optionMapping;
    /**
     * 取值说明
     */
    private String options = "0-选项一|1-选项二|2-选项三";
    /**
     * 数据类型用户友好名称。
     */
    private String caption = "选项";

    @Override
    public String caption() {
        return caption;
    }

    @Override
    public Integer parse(String text, Integer defaultValue) {
        if (!StringUtils.isNumeric(text)) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException ex) {
            return defaultValue;
        }
    }

    @Override
    public Integer parse(String text) throws IllegalArgumentException {
        if (!StringUtils.isNumeric(text)) {
            throw new IllegalArgumentException(text + " 无法转换成" + caption());
        }
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException ex) {
            throw new IllegalArgumentException(text + " 无法转换成" + caption(), ex);
        }
    }

    /**
     * 取值说明
     *
     * @return the options
     */
    public Map<Integer, String> getOptions() {
        if (optionMapping == null) {
            if (StringUtils.isBlank(options)) {
                throw new IllegalStateException("枚举类型——" + caption + "无可选值");
            }
            optionMapping = new LinkedHashMap<Integer, String>();
            String[] opts = options.split("[|,]");
            for (int i = 0; i < opts.length; i++) {
                String[] ss = opts[i].split("-");
                Integer key;
                String value;
                if (ss.length == 2) {
                    try {
                        key = Integer.parseInt(ss[0]);
                    } catch (NumberFormatException ex) {
                        key = i;
                    }
                    value = ss[1];
                } else {
                    key = i;
                    value = ss[0];
                }
                optionMapping.put(key, value);
            }
        }
        return optionMapping;
    }

    /**
     * 取值说明
     *
     * @param options the options to set
     */
    public void setOptions(String options) {
        this.options = options;
    }

    /**
     * 数据类型用户友好名称。
     *
     * @param caption the caption to set
     */
    public void setCaption(String caption) {
        this.caption = caption;
    }

}
